#!/usr/bin/perl
#
# be sure to enable automove-background extension too

use IO::Socket;
    
my $display = $ENV{'DISPLAY'};
$display =~ s/://g;

sub on_start {
    my ( $self ) = @_;

    # Kick off IO Watcher...
    $self->start_iow;

}

sub start_iow {
    my ( $self ) = @_;
    my $sock;

    # If we have a tcp loop happening, kill it off
    #delete $self->{connection_timer};

    # Connect to daemon
    #$sock = new IO::Socket::INET (
    #            PeerAddr => 'localhost',
    #            PeerPort => '37373',
    #            Proto => 'tcp',
    #            );
    my $sock = new IO::Socket::UNIX(
                 Peer      => '/tmp/wallpaper_socket',
                 Type      => SOCK_STREAM,
                 Timeout   => 10
             );

    # If there's no connection, start timer again and die off...
    if (! $sock ) {
        connection_loop( $self );
        die( "No connection yet\n" );
    } else {
        #print "Connection Established\n"; 
        # We have liftoff!
        print $sock "urxvt:$display\n";
        
        my $pixmap = socket_read( $sock );
        my ( $startphoto ) = $pixmap =~ /.*\ :\ .*\ :\ (.*)/;

        $self->cmd_parse( "\033]20;$startphoto\007" ); 

        $self->{socket} = urxvt::iow
         ->new
         ->fd (fileno $sock)
         ->events (urxvt::EVENT_READ)
         ->start
         ->cb (
            sub {
                my ($iow, $revents) = @_;
                while( <$sock>) {
                  last if ( $_ eq "END\n" );
                    if ( $_ =~ /^UPDATE/ ) {           
                        my ( $sent_display, $usephoto ) = $_ =~ /.*\ :\ (.*)\ :\ (.*)/;
                        if ( $display eq $sent_display ) {
                          #print "Photo update recieved\n";
                          $self->cmd_parse( "\033]20;$usephoto\007" ); 
                        }
                    }
                }
                delete $self->{socket};
                #print "Connection Lost (maybe)\n";
                $self->start_iow;
            } 
        ); 
    }

}

sub connection_loop {
    my ( $self ) = @_;
    $self->{ connection_timer } = urxvt::timer
    ->new
    ->start( 10 + int urxvt::NOW )
    ->interval( 0 ) # Only fire once
    ->cb( 
        sub {
            #print "Connection Timer reached\n"; 
            $self->start_iow;
        } 
    );
}

sub socket_read {
    my ( $socket ) = @_;
    my $data;

    while(<$socket>) {
        last if ( $_ eq "END\n" );
        $data .= $_;
    }
    return $data;
}
